import warnings
warnings.warn("qturboframe.public_ui.ucf_h_ui.timer模块已被废弃，替代模块为qturboframe.public_ui.h_ui.timer", DeprecationWarning)

from qturboframe.lib.report.log import logger
from qturboframe.lib.ranorex.exceptions import CsClientError
from qturboframe.lib.ranorex.web_element.web_element import WebElement
from qturboframe.lib.ranorex.web_element.div_tag import DivTag
from qturboframe.lib.ranorex.web_element.input_tag import InputTag
from qturboframe.lib.ranorex.web_element.li_tag import LiTag
from qturboframe.lib.ranorex.web_element.i_tag import ITag
from qturboframe.lib.utils.__datatime_format__ import split_time
from qturboframe.lib.utils.check import CheckBasic
from qturboframe.lib.ranorex.common.ranorex_path_to_xpath import convert_ranorexpath_to_xpath
from ..ucf_base_element import BaseElement
from .button import Button


class Timer(BaseElement, CheckBasic):
    """
    hui的时间控件操作

    :Attributes:
     - calendar_div: 日历控件的弹出框div元素
    """

    time_div = WebElement

    def __init__(self, element_para, father=None, timeout=10000):
        super().__init__(element_para, father, timeout)
        class_list = self._element.get_attribute('class').split(' ')
        if 'h-date-picker' not in class_list:
            self._element = self._element.find_element_by_attribute(
                'xpath', './ancestor::div[@class~"h-date-picker"]', timeout=self.timeout)
        self._element = DivTag(self._element.control)

    def set_value(self, value):
        """
        hui时间控件赋值

        :Args:
         - value: 时间值

        :Usage:
         - timer.set_value('20:20:20')
         - timer.set_value('20:20:20 - 21:21:21')
        """
        # 数据驱动选项
        text_list = value.split(' - ')
        if len(text_list) == 1:
            self.set_value_for_single(text_list[0])
        elif len(text_list) == 2:
            self.set_value_for_range(text_list[0], text_list[1])
        else:
            raise AttributeError('时间参数格式不规范！')

    def set_value_for_single(self, value):
        """
        hui时间组件赋值

        :Args:
         - value: 时间值

        :Usage:
         - timer.set_value_for_single('20:20:20')
        """
        re_displaynone = 'none'
        time_input = InputTag(self._element.find_element_by_attribute(
            'xpath', './/input', timeout=self.timeout).control)
        time_input.secure_click()
        time_div = self._element.exist(
            'xpath', './/div[@class~\'h-select-dropdown\']', timeout=100)
        if not time_div:
            time_div = self._driver.find_element_by_attribute(
                'xpath', './body/div[@class~\'h-select-dropdown\']', 'style:display: block;',
                timeout=self.timeout)
        self.time_div = DivTag(time_div.control)
        hour, minute, second = split_time(value)
        # 选择hour
        div_style = self.time_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_hour(hour)
        # 选择minute
        div_style = self.time_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_minute(minute)
        # 选择second
        div_style = self.time_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_second(second)
        # 确定
        div_style = self.time_div.get_style('display')
        if re_displaynone not in div_style:
            confirm_div = self.time_div.exist('xpath', './/div[@class~\'h-picker-confirm\']', timeout=100)
            if confirm_div:
                Button({'xpath': './/button[@class~\'h-btn\' and @innertext=\'确定\']'}, confirm_div, 1000).click()
            else:
                time_input.press_keys('{ESCAPE}')

    def set_value_for_range(self, value1, value2):
        """
        hui时间范围组件赋值

        :Args:
         - value: 时间范围值

        :Usage:
         - timer.set_value_for_range('20:20:20 - 21:21:21')
        """
        re_displaynone = 'none'
        time_input = InputTag(self._element.find_element_by_attribute(
            'xpath', './/input', timeout=self.timeout).control)
        time_input.secure_click()
        time_div = self._element.exist(
            'xpath', './/div[@class~\'h-select-dropdown\']', timeout=100)
        if not time_div:
            time_div = self._driver.find_element_by_attribute(
                'xpath', './body/div[@class~\'h-select-dropdown\']', 'style:display: block;',
                timeout=self.timeout)
        self.time_div = DivTag(time_div.control)
        time_div_left = self.time_div.find_element_by_attribute(
            'xpath', './/div[@class~\'h-time-picker-with-range\']/'
                     'div[@class~\'h-picker-panel-body\']/div[@class~\'h-picker-panel-content-left\']',
            timeout=self.timeout)
        time_div_right = self.time_div.find_element_by_attribute(
            'xpath', './/div[@class~\'h-time-picker-with-range\']/'
                     'div[@class~\'h-picker-panel-body\']/div[@class~\'h-picker-panel-content-right\']',
            timeout=self.timeout)
        hour1, minute1, second1 = split_time(value1)
        hour2, minute2, second2 = split_time(value2)
        temp_div = self.time_div
        self.time_div = time_div_left
        # 选择hour1
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_hour(hour1)
        # 选择minute1
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_minute(minute1)
        # 选择second1
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_second(second1)
        self.time_div = time_div_right
        # 选择hour2
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_hour(hour2)
        # 选择minute2
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_minute(minute2)
        # 选择second2
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            self.__set_second(second2)
        # 确定
        div_style = temp_div.get_style('display')
        if re_displaynone not in div_style:
            confirm_div = temp_div.exist('xpath', './/div[@class~\'h-picker-confirm\']', timeout=100)
            if confirm_div:
                Button({'xpath': './/button[@class~\'h-btn\' and @innertext=\'确定\']'}, confirm_div, 100).click()
            else:
                time_input.press_keys('{ESCAPE}')

    def __set_hour(self, hour):
        re_displaynone = 'none'
        head_div = DivTag(self.time_div.find_elements_by_attribute(
            'xpath', './/div[@class~\'h-time-picker-cells\']/div[@class~\'h-time-picker-cells-list\']',
            timeout=self.timeout)[0].control)
        div_style = head_div.get_style('display')
        if re_displaynone not in div_style:
            hour_li = LiTag(head_div.find_elements_by_attribute('xpath',
                './/ul[@class~\'h-time-picker-cells-ul\']/li[@class~\'h-time-picker-cells-cell\']',
                                                                timeout=self.timeout)[int(hour)].control)
            self._driver.scroll_into_view(convert_ranorexpath_to_xpath(hour_li.get_path()))
            hour_li.focus()
            hour_li.secure_click()

    def __set_minute(self, minute):
        re_displaynone = 'none'
        head_div = DivTag(self.time_div.find_elements_by_attribute(
            'xpath', './/div[@class~\'h-time-picker-cells\']/div[@class~\'h-time-picker-cells-list\']',
            timeout=self.timeout)[1].control)
        div_style = head_div.get_style('display')
        if re_displaynone not in div_style:
            minute_li = LiTag(head_div.find_elements_by_attribute('xpath',
                './/ul[@class~\'h-time-picker-cells-ul\']/li[@class~\'h-time-picker-cells-cell\']',
                                                                  timeout=self.timeout)[int(minute)].control)

            self._driver.scroll_into_view(convert_ranorexpath_to_xpath(minute_li.get_path()))
            minute_li.focus()
            minute_li.secure_click()

    def __set_second(self, second):
        re_displaynone = 'none'
        head_div = DivTag(self.time_div.find_elements_by_attribute(
            'xpath', './/div[@class~\'h-time-picker-cells\']/div[@class~\'h-time-picker-cells-list\']',
            timeout=self.timeout)[2].control)
        div_style = head_div.get_style('display')
        if re_displaynone not in div_style:
            second_li = LiTag(head_div.find_elements_by_attribute('xpath',
                './/ul[@class~\'h-time-picker-cells-ul\']/li[@class~\'h-time-picker-cells-cell\']',
                                                                  timeout=self.timeout)[int(second)].control)

            self._driver.scroll_into_view(convert_ranorexpath_to_xpath(second_li.get_path()))
            second_li.focus()
            second_li.secure_click()

    def clear(self):
        """
        hui时间控件值清除选项值

        :Example:
         - 例: timer.clear()
        """
        self._element.move_to()
        clear_i = ITag(self._element.exist(
            'xpath', './/div[@class~\'h-select-selection\']/i[@class~\'h-icon-close\']',
            timeout=self.timeout).control)
        if clear_i:
            clear_i.secure_click()
        else:
            raise CsClientError('没有清除按钮，无法删除！')

    def is_default(self, value):
        """
        检查hui时间控件默认值

        :Args:
         - value: 待检查的选项值

        :Returns:
            匹配返回True，否则返回False

        :Example:
         - 例: timer.is_default('12:10:08')
        """
        inputele = InputTag(self._element.find_element_by_attribute(
            'xpath', './/input', timeout=self.timeout).control)
        inputele.focus()
        if inputele.get_attribute('value'):
            text = inputele.get_attribute('value')
        elif inputele.get_attribute('placeholder'):
            text = inputele.get_attribute('placeholder')
        elif inputele.get_attribute('defaultValue'):
            text = inputele.get_attribute('defaultValue')
        else:
            text = ''
        if text:
            if text == value:
                return True
            else:
                logger.error('默认值不匹配！')
                return False
        else:
            logger.error('没有默认值！')
            return False

    def is_nonnull(self):
        '''
        检查hui时间控件是否有非空属性

        :Returns:
            非空返回True，否则返回False

        :Example:
         - 例: timer.is_nonnull()
        '''
        self._element.focus()
        form_item = DivTag(self._element.find_element_by_attribute(
            'xpath', './ancestor::div[@class~\'h-form-item-content\']/'
                     'parent::div[@class~\'h-form-item\']', timeout=self.timeout).control)
        item_class_list = form_item.get_attribute('class').split(' ')
        if 'h-form-item-required' in item_class_list:
            return True
        else:
            return False

    def check_default(self, value):
        '''
        校验hui时间控件默认值

        :Args:
         - value: 待检查的选项值

        :Raises:
            SeleniumError: 日历控件默认值校验不通过

        :Example:
         - 例: timer.check_default('08:10:12')
        '''
        if not self.is_default(value):
            raise CsClientError('日历控件默认值校验不通过！')

    def check_nonull(self):
        '''
        校验hui时间控件是否非空

        :Raises:
            SeleniumError: 日历控件非空校验不通过

        :Example:
         - 例: timer.check_nonull()
        '''
        if not self.is_nonnull():
            raise CsClientError('日历控件非空校验不通过！')